package 第四周;

/**
 * @author xhw
 */

public class 有效的括号 {
    public static void main(String[] args) {
        String s = "{[(]}";
        boolean isValid = isValid(s);
        System.out.println("字符串 \"" + s + "\" 是否为有效的括号： " + isValid);
    }

    public static boolean isValid(String s) {
        int[] bracketCount = new int[3]; // 0 for '(', 1 for '{', 2 for '['
        int[] stack = new int[s.length()]; // 用来存储括号类型的 "栈"
        int top = -1;

        for (char c : s.toCharArray()) {
            if (c == '(') {
                bracketCount[0]++;
                stack[++top] = 0;
            } else if (c == '{') {
                bracketCount[1]++;
                stack[++top] = 1;
            } else if (c == '[') {
                bracketCount[2]++;
                stack[++top] = 2;
            } else if (c == ')' && bracketCount[0] > 0 && top != -1 && stack[top] == 0) {
                bracketCount[0]--;
                top--;
            } else if (c == '}' && bracketCount[1] > 0 && top != -1 && stack[top] == 1) {
                bracketCount[1]--;
                top--;
            } else if (c == ']' && bracketCount[2] > 0 && top != -1 && stack[top] == 2) {
                bracketCount[2]--;
                top--;
            } else {
                // 如果不是开括号，而且栈为空或不匹配
                return false;
            }
        }

        return top == -1; // 如果所有开括号都被正确匹配，栈应该为空
    }
}